package cn.zhiwen.controller;

import cn.zhiwen.config.DataSourceHolder;
import cn.zhiwen.entity.Animal;
import cn.zhiwen.entity.BaseRequestModelII;
import cn.zhiwen.entity.BaseResponseModel;
import cn.zhiwen.entity.CustomerRequest;
import cn.zhiwen.entity.DealerIdCodeName;
import cn.zhiwen.entity.DealerOfBrand;
import cn.zhiwen.entity.UserData;
import cn.zhiwen.enumname.RespMsgEnum;
import cn.zhiwen.service.CustomerService;
import cn.zhiwen.service.RegisterUserService;
import cn.zhiwen.service.SyncAddUserService;
import cn.zhiwen.util.ResultUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/10/22 15:01
 * @Description:
 */
@RestController
public class RegisterUserWithPoiController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RegisterUserService registerUserService;

    @Autowired
    private SyncAddUserService syncAddUserService;

    @RequestMapping(value = "/demo")
    public Animal demo() {
        Animal animal = new Animal();
        animal.setAge(registerUserService.demo());
        animal.setName("demo");
        return animal;
    }

    @RequestMapping(value = "/register")
    public String registerUser() {
        BufferedWriter bufferedWriter = null;
        BufferedWriter bufferedWriter1 = null;
        BufferedWriter bufferedWriter2 = null;
        try {
            //创建resttemple
            RestTemplate restTemplate = new RestTemplate();


            //记录文件数据信息
            final int[] countEcelc = {0, 0, 0};
            //保存文件
            ArrayList<File> files = new ArrayList<>();

            String[] vipArray = new String[]{"V1", "V2", "V3"};

            File file = new File("C:\\Users\\admin\\Desktop\\1111");

            //创建文件记录日志
            File file2 = new File("C:\\Users\\admin\\Desktop\\1111\\log.txt");
            if (!file2.exists()) {
                file2.createNewFile();
            }
            File file3 = new File("C:\\Users\\admin\\Desktop\\1111\\data.txt");
            if (!file3.exists()) {
                file3.createNewFile();
            }
            File file4 = new File("C:\\Users\\admin\\Desktop\\1111\\error.txt");
            if (!file4.exists()) {
                file4.createNewFile();
            }

            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2, true)));
            bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file3, true)));
            bufferedWriter2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file4, true)));
            List<File> allExcel = getAllExcel(file, files, countEcelc);
            for (File file1 : allExcel) {
                FileInputStream fileInputStream = new FileInputStream(file1);
                //POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fileInputStream);
                //HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
                XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
                //获取第一个工作簿
                XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
                LinkedHashMap<String, String> dealrDolWithSap = new LinkedHashMap<String, String>();
                if (sheetAt != null) {
                    int rownum = 9;
                    int rownum1 = 1;
                    try {
                        while (true) {
                            XSSFRow row = sheetAt.getRow(rownum++);
                            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                            dealrDolWithSap.put(row.getCell(0).toString(), "M" + row.getCell(1).getStringCellValue());
                        }
                    } catch (Exception e) {
                        bufferedWriter.write(
                                file1.getName() + dealrDolWithSap.toString() + "\r\n"
                        );
                    }

                    //获取用户信息
                    XSSFSheet sheetAt1 = xssfWorkbook.getSheetAt(1);
                    ArrayList<UserData> userDataList = new ArrayList<>();
                    try {
                        while (true) {
                            UserData userData = new UserData();
                            XSSFRow row = sheetAt1.getRow(rownum1++);
                            if (row == null) {
                                break;
                            }
                            //保存经销商code
                            String delearCode = judgeAndLog(bufferedWriter, row, dealrDolWithSap, file1, 0, "error:无法查询到经销商code：");

                            //保存用户姓名
                            String userName = judgeAndLog(bufferedWriter, row, file1, 2, "error:无法查询到经销商用户Name：");
                            //手机号
                            if (row.getCell(3) == null) {
                                bufferedWriter.write(
                                        "error:手机号为空" + file.getName() + "\r\n"
                                );
                            } else {
                                row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                            }

                            String linkCode = judgeAndLog(bufferedWriter, row, file1, 3, "error:无法查询到经销商用户NamelinkCode：");

                            //判断动作
                            String action = judgeAndLog(bufferedWriter, row, file1, 5, "error:无法查询到经销商用户action：");
                            //保存vip等级
                            String vip = judgeAndLog(bufferedWriter, row, file1, 1, "error:无vip等级权限：");
                            //详细区分vip
                            for (String s : vipArray) {
                                if (vip != null && vip != "" && vip.contains(s)) {
                                    vip = s;
                                    break;
                                }
                            }
                            //统一赋值
                            userData.setUserNanme(userName);
                            userData.setLinkCode(linkCode);
                            userData.setDelearCode(delearCode);
                            userData.setAction(action);
                            userData.setVips(vip);

                            //对手机号进行校验
                            if (!Pattern.matches("^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", linkCode)) {
                                bufferedWriter.write(
                                        "error:手机号有问题" + userData + "\r\n"
                                );
                                bufferedWriter1.write(
                                        "error:手机号有问题对象" + userData + "\r\n"
                                );
                                linkCode = "";
                            }

                            //如果对象中属性都为空 则报错
                            if (judgeIsNullOrEmpty(userData)) {
                                bufferedWriter.write(
                                        "error:对象属性全部为空" + file1.getName() + userDataList.toString() + "\r\n"
                                );
                                break;
                            }
                            //判断是否存在部分为空数据
                            if (judgeObejectIsNullOrEmpty(userData)) {
                                bufferedWriter.write(
                                        "error:对象属性存在为空" + userData.toString() + "\r\n"
                                );
                            } else {
                                userDataList.add(userData);
                                bufferedWriter.write(
                                        "info:打印对象数据" + userData.toString() + "\r\n"
                                );
                            }

                        }
                    } catch (IOException e) {
                        bufferedWriter.write(
                                "IOException" + file1.getName() + userDataList.toString() + "\r\n"
                        );
                    }

                    //进行逻辑判断 注册用户
                    if (userDataList.size() == 0) {
                        bufferedWriter.write(
                                "error:没有获取" + file1.getName() + "数据" + "\r\n"
                        );
                    }

                    for (UserData userData : userDataList) {
                        //设置参数
                        BaseRequestModelII<CustomerRequest> customerRequestBaseRequestModelII = new BaseRequestModelII<>();
                        //设置token
                        customerRequestBaseRequestModelII.setToken("35612664_114844ddfe904876a6b5106335e1ed29");
                        customerRequestBaseRequestModelII.setUserId("35612664");
                        customerRequestBaseRequestModelII.setForm(3);

                        CustomerRequest customerRequest = new CustomerRequest();
                        customerRequest.setCustname(userData.getUserNanme());
                        customerRequest.setCusttype("3");
                        customerRequest.setCanReceive(1);
                        customerRequest.setLinktel(userData.getLinkCode());

                        ArrayList<DealerOfBrand> dealerOfBrands = new ArrayList<>();
                        DealerOfBrand dealerOfBrand = new DealerOfBrand();
                        //上汽汽车
                        dealerOfBrand.setBrandCode("1279-SMC");
                        dealerOfBrand.setBrandName("增加");
                        dealerOfBrands.add(dealerOfBrand);

                        DealerIdCodeName dealerIdCodeName = registerUserService.queryDeleaCode(userData);
                        if (dealerIdCodeName == null) {
                            bufferedWriter1.write("info添加失败的数据对象，经销商不存在" + userData.toString() + "\r\n");
                            continue;
                        }
                        if (dealerIdCodeName.getDealerIdCodes() == null || dealerIdCodeName.getDealerIdCodes().equals("")) {
                            bufferedWriter1.write("info添加失败的数据对象，经销商不存在" + userData.toString() + "\r\n");
                            continue;
                        }

                        ArrayList<String> dealerIdCodes = new ArrayList<>();
                        dealerIdCodes.add(dealerIdCodeName.getDealerIdCodes());
                        //添加经销商数据
                        dealerOfBrand.setDealerIdCodes(dealerIdCodes);

                        //设置多个经销商数据
                        customerRequest.setDealerOfBrands(dealerOfBrands);
                        customerRequestBaseRequestModelII.setReqData(customerRequest);


//                        String userJson = JSON.toJSONString(customerRequestBaseRequestModelII);
//
//                        //设置请求头
//                        HttpHeaders headers = new HttpHeaders();
//                        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//                        headers.add("Content-Type", "application/json;charset=UTF-8");
//                        HttpEntity<String> formEntity = new HttpEntity<String>(userJson, headers);
//
//                        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, formEntity, String.class);
//                        String body = stringResponseEntity.getBody();
//                        BaseResponseModel baseResponseModel = JSON.parseObject(body, BaseResponseModel.class);


                        BaseResponseModel<Boolean> baseResponseModel = insertCustomer(customerRequestBaseRequestModelII);

                        if (baseResponseModel.getRepMsg().equals("成功")) {
                            DataSourceHolder.setDataSource("0");
                            registerUserService.insertVip(userData);
                            countEcelc[2]++;
                            bufferedWriter1.write("info添加成功的数据对象" + baseResponseModel.toJsonString() + "\r\n");
                        } else {
                            bufferedWriter2.write("error添加失败的数据对象" + userData.toString() + "\r\n" + baseResponseModel.toJsonString() + "\r\n");
                        }
                    }

                    //关流
                    xssfWorkbook.close();
                    fileInputStream.close();
                }
            }

            bufferedWriter.write(
                    "共有文件：" + countEcelc[0] + "\r\n"
            );
            bufferedWriter.write(
                    "共有excel：" + allExcel.size() + "\r\n"
            );
            bufferedWriter.write(
                    "非excel文件：" + countEcelc[1] + "\r\n"
            );
            bufferedWriter.write(
                    "注册成功人数：" + countEcelc[2] + "\r\n"
            );


        } catch (Exception e) {
            e.printStackTrace();
            return "no success";
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
                if (bufferedWriter1 != null) {
                    bufferedWriter1.flush();
                    bufferedWriter1.close();
                }
                if (bufferedWriter2 != null) {
                    bufferedWriter2.flush();
                    bufferedWriter2.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "success";
    }

    //获取所有excel文件
    public static List<File> getAllExcel(File file, List list, final int[] countEcelc) {
        try {
            File[] files = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if (pathname.isDirectory()) {
                        getAllExcel(pathname, list, countEcelc);
                        countEcelc[0]++;
                        return false;
                    }
                    if (!pathname.getName().contains(".xlsx") || !pathname.getName().contains(".xls")) {
                        countEcelc[1]++;
                        return false;
                    }
                    return true;
                }
            });
            for (File file1 : files) {
                list.add(file1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    //判断对象所有属性是否为null 或者 ""
    public static boolean judgeIsNullOrEmpty(Object object) throws IllegalAccessException {
        Class<?> aClass = object.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        boolean flag = false;
        int count = 0;
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            Object val = declaredField.get(object);
            if (val == null || val == "") {
                count++;
            }
        }
        if (count == declaredFields.length) {
            flag = true;
        }
        return flag;
    }

    //判断对象是否存在属性是否为null 或者 ""
    public static boolean judgeObejectIsNullOrEmpty(Object object) throws IllegalAccessException {
        Class<?> aClass = object.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        boolean flag = false;
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            Object val = declaredField.get(object);
            if (val == null || val == "") {
                flag = true;
                break;
            }
        }
        return flag;
    }

    public static String judgeAndLog(BufferedWriter bufferedWriter, Row row, Map<String, String> map, File file, int count, String errorCause) throws IOException {
        Cell cell = row.getCell(count);
        if (cell == null) {
            return "";
        }
        String delearCode = map.get(cell.toString().trim());
        if (delearCode == null || delearCode.equals("")) {
            bufferedWriter.write(
                    errorCause + file.getName() + "\r\n"
            );
        }
        return delearCode;
    }

    public static String judgeAndLog(BufferedWriter bufferedWriter, Row row, File file, int count, String errorCause) throws IOException {
        Cell cell = row.getCell(count);
        if (cell == null) {
            return "";
        }
        String data = cell.toString().trim();
        if (data == null || data.equals("")) {
            bufferedWriter.write(
                    "error:无法查询到经销商code：" + errorCause + file.getName() + "\r\n"
            );
        }
        return data;
    }


    public BaseResponseModel<Boolean> insertCustomer(BaseRequestModelII<CustomerRequest> request) {
//        Log.info("===================新增用户开始");
        try {
            Integer count = 0;
            Integer customerId = customerService.insertIntoCustomerRequest(request.getReqData());
            if (customerId == 000010) {
                BaseResponseModel responseModel = ResultUtil.setError(RespMsgEnum.hadBeen_Registed);
                return responseModel;
            }
            if (customerId != null) {
                CustomerRequest reqData = request.getReqData();
                reqData.setId(customerId);
                if (reqData.getCusttype().equals("3")) {
                    //切换数据源
                    DataSourceHolder.setDataSource("1");
                    count = customerService.insertUserAndRole(reqData);
                }
                if (count == 1) {
                    BaseResponseModel<Boolean> responseModel = ResultUtil.setSuccess(true);
                    return responseModel;
                } else {
                    BaseResponseModel responseModel = ResultUtil.setError(RespMsgEnum.OPERAT_ERROR);
                    return responseModel;
                }
            } else {
                BaseResponseModel responseModel = ResultUtil.setError(RespMsgEnum.OPERAT_ERROR);
                return responseModel;
            }

        } catch (Exception e) {
//            Log.error("新增用户异常", e);
            BaseResponseModel responseModel = ResultUtil.setError(RespMsgEnum.OPERAT_ERROR);
            return responseModel;
        }
    }

}
